<template>
  <el-row style="min-width: 1500px">
    <el-col :span="24">
      <div>
        <div class="box">
          <div class="box-heard">
            <div>
              <div style="line-height: 40px">素材管理</div>
              <el-divider />
            </div>
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <el-upload
                  class="upload-demo"
                  action=""
                  ref="upload"
                  :file-list="fileList"
                  :limit="9"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :auto-upload="false"
                  :show-file-list="false"
                  :multiple="true"
                  accept=""
                >
                  <el-button
                    size="large"
                    type="primary"
                    v-has="'materialUpload'"
                    >上传素材</el-button
                  >
                </el-upload>
                <el-button
                  size="large"
                  style="margin: 0 15px; color: #0daeff; border-color: #0daeff"
                  @click="dialogFormVisible = true"
                  v-has="'materialUpload'"
                  >创建目录</el-button
                >
                <el-button
                  size="large"
                  :disabled="isdelect"
                  @click="delectClick"
                  v-has="'materialdeleteBcs'"
                  >删除</el-button
                >
                <el-button
                  size="large"
                  :disabled="isdelect"
                  @click="moves"
                  v-has="'materialMove'"
                  >移动</el-button
                >
                <el-button size="large" v-if="ishome" @click="paste"
                  >粘贴</el-button
                >
                <span
                  v-if="isdone"
                  style="
                    display: flex;
                    align-items: center;
                    margin: 0 7px;
                    color: #5e6369;
                  "
                  >已选
                  <span style="color: #303233; margin: 0 5px">{{
                    length
                  }}</span>
                  个文件</span
                >
              </div>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <div style="margin-right: 10px">
                  <el-select
                    v-model="select"
                    ref="select"
                    clearable
                    placeholder="请选择类型"
                    @change="buootClick"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
                <div>
                  <el-input
                    v-model="input1"
                    class="w-50 m-2"
                    placeholder="输入素材名或用户名"
                    style="cursor: pointer"
                    @change="SearchClick()"
                  >
                    <template #suffix>
                      <el-image
                        :src="require('../../assets/sou.png')"
                        style="width: 16px; height: 16px"
                        alt=""
                        @click="SearchClick()"
                      />
                    </template>
                  </el-input>
                </div>
              </div>
            </div>
            <el-divider />
            <!-- Form -->
            <el-breadcrumb>
              <el-breadcrumb-item
                to="/advertising/materialManagement"
                v-for="(item, index) in genOpenInfo"
                :key="index"
                replace
              >
                <span @click="openId(item.id, item)">{{ item.name }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
            <el-dialog
              v-model="dialogFormVisible"
              title="创建目录"
              width="30%"
              center
              @close="closeClick"
            >
              <el-form :model="form">
                <el-form-item label="目录名" :label-width="formLabelWidth">
                  <el-input
                    v-model="form.name"
                    autocomplete="off"
                    style="width: 180px"
                    maxlength="8"
                  />
                  <div style="color: rgb(143, 138, 138); margin: 0 5px">
                    文件夹名只能8个字符
                  </div>
                </el-form-item>
              </el-form>

              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialogFormVisible = false">取消</el-button>
                  <el-button type="primary" @click="opeName"> 确认 </el-button>
                </span>
              </template>
            </el-dialog>
            <!-- 进度条放小 -->
            <el-dialog
              align-center
              v-model="visible"
              :show-close="false"
              style="height: 50px"
            >
              <template #header="{ close, titleId, titleClass }">
                <div class="my-header">
                  <div style="display: flex; align-items: center">
                    <div>
                      <el-image
                        style="
                          vertical-align: middle;
                          width: 16px;
                          height: 16px;
                        "
                        :src="require('../../assets/topj.png')"
                        alt=""
                      />
                    </div>
                    <span
                      style="
                        font-weight: 700;
                        margin-left: 5px;
                        color: #0daeff;
                        font-size: 14px;
                      "
                      >{{ uploadLists.status
                      }}{{ uploadLists.length }} 个上传任务正在进行中,{{
                        ager.length
                      }}个上传失败,{{ uploadLists.length }}个上传成功</span
                    >
                  </div>
                  <div>
                    <el-image
                      @click="btnlocse"
                      v-if="loses"
                      style="
                        vertical-align: middle;
                        margin-left: 5px;
                        width: 16px;
                        height: 16px;
                      "
                      :src="require('../../assets/suo.png')"
                      alt=""
                    />
                    <el-image
                      @click="btnlocses"
                      v-if="losess"
                      style="
                        vertical-align: middle;
                        margin-left: 5px;
                        width: 16px;
                        height: 16px;
                      "
                      :src="require('../../assets/magnify.png')"
                      alt=""
                    />
                    <el-image
                      @click="close"
                      style="
                        vertical-align: middle;
                        margin-left: 5px;
                        width: 16px;
                        height: 16px;
                      "
                      :src="require('../../assets/loses.png')"
                      alt=""
                    />
                  </div>
                </div>
              </template>
            </el-dialog>
            <!-- 进度条 -->
            <el-dialog align-center v-model="outerVisible" :show-close="false">
              <template #header="{ close, titleId, titleClass }">
                <div class="my-header">
                  <div style="display: flex; align-items: center">
                    <div class="add"></div>
                    <span style="font-weight: 700; margin-left: 5px"
                      >上传任务</span
                    >
                  </div>
                  <div>
                    <el-image
                      @click="btnlocse"
                      v-if="loses"
                      style="
                        vertical-align: middle;
                        margin-left: 5px;
                        width: 16px;
                        height: 16px;
                      "
                      :src="require('../../assets/suo.png')"
                      alt=""
                    />
                    <el-image
                      @click="btnlocses"
                      v-if="losess"
                      style="
                        vertical-align: middle;
                        margin-left: 5px;
                        width: 16px;
                        height: 16px;
                      "
                      :src="require('../../assets/magnify.png')"
                      alt=""
                    />
                    <el-image
                      @click="close"
                      style="
                        vertical-align: middle;
                        margin-left: 5px;
                        width: 16px;
                        height: 16px;
                      "
                      :src="require('../../assets/loses.png')"
                      alt=""
                    />
                  </div>
                </div>
              </template>

              <!-- 进度条 -->

              <div>
                <el-table
                  :header-cell-style="{
                    backgroundColor: '#F7F7F7',
                  }"
                  class="table"
                  :data="uploadLists"
                  style="width: 100%"
                  align="center"
                >
                  <el-table-column
                    prop="uploadName"
                    label="文件名称"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column prop="size" label="文件大小" align="center">
                  </el-table-column>
                  <el-table-column
                    prop="status"
                    label="上传状态"
                    align="center"
                  >
                    <template #default="{ row }">
                      <div v-if="row.percentage == 100">
                        <el-image
                          :src="require('../../assets/sessus.png')"
                          style="
                            vertical-align: middle;
                            margin-left: 5px;
                            width: 16px;
                            height: 16px;
                          "
                          alt=""
                        />
                        完成
                      </div>
                      <div v-if="ishowss" style="color: red">
                        <el-image
                          style="
                            vertical-align: middle;
                            margin-left: 5px;
                            width: 16px;
                            height: 16px;
                          "
                          :src="require('../../assets/lose.png')"
                          alt=""
                        />
                        失败
                      </div>
                      <div v-if="row.percentage !== 100">
                        {{ row.status }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="上传进度" align="center">
                    <template #default="{ row }">
                      <div v-if="ishowss">0%</div>
                      <div v-else>{{ row.percentage }}%</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                      <div v-if="row.percentage < 100">
                        <el-button
                          style="margin-left: 10px"
                          size="small"
                          type="success"
                          v-if="ishowss"
                          @click="resumeUpload"
                          >重试</el-button
                        >
                        <el-button
                          style="margin-left: 10px"
                          size="small"
                          type="success"
                          @click="stopUplosd"
                          v-if="ishows"
                          >停止</el-button
                        >
                      </div>

                      <el-button
                        style="margin-left: 10px"
                        size="small"
                        type="success"
                        v-if="row.percentage == 100"
                        @click="uploadLists = ''"
                        >清除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-dialog>
            <!-- 修改文件名 -->
            <el-dialog
              v-model="centerDialogVisible"
              title="编辑"
              width="30%"
              center
            >
              <el-form :model="form">
                <el-form-item label="文件名" :label-width="formLabelWidth">
                  <el-input
                    v-model="form.monicker"
                    autocomplete="off"
                    style="width: 280px"
                    maxlength="32"
                    placeholder="中文、字母、数字、下划线、横线,1-32位"
                  />
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="centerDialogVisible = false"
                    >取消</el-button
                  >
                  <el-button type="primary" @click="monickerClick">
                    确认
                  </el-button>
                </span>
              </template>
            </el-dialog>
            <!-- 点击预览图片 -->
            <el-dialog v-model="dialogTableVisible" :show-close="false">
              <template #header="{ close, titleId, titleClass }">
                <div class="my-header">
                  <div
                    style="
                      margin: 7px 0px;
                      width: 100%;
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                    "
                  >
                    <div>
                      <span style="color: #0daeff; height: 18px">
                        |
                        <span style="color: #303233; font-weight: 700"
                          >预览</span
                        >
                      </span>
                    </div>
                    <div
                      style="text-align: center; height: 21px; display: flex"
                    >
                      <div style="margin: 0 5px">
                        {{ editInfo.name }}.{{ editInfo.fileSuffix }}
                      </div>

                      <div style="line-height: 21px; cursor: pointer">
                        <el-icon class="el-icon--left" @click="close"
                          ><Close
                        /></el-icon>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
              <div style="text-align: center" v-if="editInfo.fileType == 0">
                <el-image
                  style="width: 100%; height: 586px"
                  :src="editInfo.fileUrl"
                />
              </div>
              <div style="text-align: center" v-if="editInfo.fileType == 1">
                <audio
                  style="width: 100%"
                  :src="editInfo.fileUrl"
                  muted
                  controls
                />
              </div>
              <div style="text-align: center" v-if="editInfo.fileType == 2">
                <video
                  style="width: 100%; height: 586px"
                  :src="editInfo.fileUrl"
                  controls
                  muted
                />
              </div>
              <div style="text-align: center" v-if="editInfo.fileType == 3">
                <iframe
                  :src="editInfo.fileUrl"
                  style="width: 100%; height: 586px"
                ></iframe>
              </div>
              <!-- 设备详情弹框 -->
              <div>
                <el-descriptions
                  :column="2"
                  border
                  style="margin: 10px 0; text-align: left"
                  label-align="center"
                >
                  <el-descriptions-item
                    label="类型"
                    label-align="right"
                    align="left"
                    label-class-name="my-label"
                    class-name="my-content"
                    color="red"
                    width="250px"
                  >
                    <span v-if="editInfo.fileType == 0">图片</span>
                    <span v-if="editInfo.fileType == 1">音频</span>
                    <span v-if="editInfo.fileType == 2">视频</span>
                    <span v-if="editInfo.fileType == 3">文档</span>
                  </el-descriptions-item>
                  <el-descriptions-item
                    label="时长"
                    label-align="right"
                    width="250px"
                    align="left"
                    v-if="editInfo.fileType == 2 || editInfo.fileType == 1"
                    >{{ editInfo.duration }}</el-descriptions-item
                  >
                  <el-descriptions-item
                    label="大小"
                    label-align="right"
                    width="250px"
                    align="left"
                  >
                    {{ editInfo.fileSize }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    label="上传时间"
                    label-align="right"
                    align="left"
                  >
                    {{ editInfo.creationDate }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="editInfo.fileType == 2 || editInfo.fileType == 0"
                    label="分辨率"
                    label-align="right"
                    align="left"
                  >
                    <span> {{ editInfo.resolutionRatio }} </span>
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-else
                    label="分辨率"
                    label-align="right"
                    align="left"
                  >
                    <span> - </span>
                  </el-descriptions-item>
                  <el-descriptions-item
                    label="上传用户"
                    label-align="right"
                    align="left"
                  >
                    {{ editInfo.lastUpdatedAccount }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </el-dialog>
            <div
              style="
                height: 100%;
                width: 100%;
                margin-top: 10px;
                background-color: #fff;
              "
            >
              <div class="table-pagination-container">
                <!-- 表格 -->
                <el-table
                  ref="multipleTableRef"
                  :header-cell-style="{ background: '#f6f7f9' }"
                  :data="listData"
                  style="height: calc(100vh - 200px); width: 100%"
                  max-height="600"
                  @select-all="handleSelectionChange"
                  @select="handleSelectionChange"
                  @cell-mouse-enter="mouseEnter"
                  @cell-mouse-leave="mouseLeave"
                >
                  <template #empty>
                    <div class="no-data">
                      <el-empty
                        :image="require('../../assets/nothave.png')"
                        style="margin-top: 30%"
                      >
                      </el-empty>
                    </div>
                  </template>
                  <el-table-column type="selection" />
                  <el-table-column label="文件名">
                    <template #default="scope">
                      <div style="display: flex; align-items: center">
                        <div v-if="scope.row.fileSuffix === 'mp4'">
                          <el-popover
                            placement="top-start"
                            :width="30"
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
                            trigger="hover"
                          >
                            <template #reference>
                              <el-image
                                :size="30"
                                :src="scope.row.fileUrl"
                                style="
                                  margin-bottom: 8px;
                                  width: 28px;
                                  height: 28px;
                                "
                              />
                            </template>
                            <template #default>
                              <div
                                class="demo-rich-conent"
                                style="
                                  display: flex;
                                  gap: 16px;
                                  flex-direction: column;
                                "
                              >
                                <el-image :src="scope.row.fileUrl" />
                              </div>
                            </template>
                          </el-popover>
                        </div>
                        <div v-if="scope.row.fileSuffix === 'mp3'">
                          <el-image
                            style="width: 28px; height: 28px"
                            :src="require('../../assets/musicd.png')"
                          />
                        </div>
                        <div v-if="scope.row.fileSuffix === 'pdf'">
                          <el-image
                            style="width: 28px; height: 28px"
                            :src="require('../../assets/pdf.png')"
                          />
                        </div>
                        <div
                          v-if="scope.row.isFile === 0"
                          @click="openClicks(scope.row)"
                        >
                          <el-image
                            style="width: 28px; height: 28px; cursor: pointer"
                            :src="require('../../assets/blus.png')"
                          />
                        </div>
                        <div
                          v-if="
                            scope.row.fileSuffix === 'png' && 'jpeg' && 'jpg'
                          "
                        >
                          <!-- 预览图片 -->
                          <el-popover
                            placement="top-start"
                            :width="30"
                            :height="30"
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
                            trigger="hover"
                          >
                            <template #reference>
                              <el-image
                                :src="scope.row.fileUrl"
                                style="width: 28px; height: 28px"
                              />
                            </template>
                            <template #default>
                              <div
                                class="demo-rich-conent"
                                style="
                                  display: flex;
                                  gap: 16px;
                                  flex-direction: column;
                                "
                              >
                                <el-image :src="scope.row.fileUrl" />
                              </div>
                            </template>
                          </el-popover>
                        </div>
                        <div
                          class="lunde"
                          style="margin: 0 10px; cursor: pointer"
                          v-if="scope.row.isFile === 0"
                          @click="openClicks(scope.row)"
                        >
                          {{ scope.row.name }}
                        </div>
                        <div
                          class="lunde"
                          style="margin: 0 10px; cursor: pointer"
                          v-else
                        >
                          {{ scope.row.name }}
                        </div>
                        <el-button
                          type="text"
                          size="small"
                          v-show="
                            showEditFileNameButton && rowId == scope.row.id
                          "
                          @click="handleClick(scope)"
                        >
                          <span class="--table-column-icon">
                            <el-icon color="#A8ADB2"><EditPen /></el-icon>
                          </span>
                          <!-- <el-image src="../../assets/edit.png" alt="" /> -->
                        </el-button>

                        <el-button
                          type="text"
                          size="small"
                          v-show="
                            showEditFileNameButton && rowId == scope.row.id
                          "
                          style="margin: 0"
                          @click="copy(scope.row.fileUrl)"
                        >
                          <span
                            class="--table-column-icon"
                            v-if="scope.row.isFile == 1"
                          >
                            <el-icon color="#A8ADB2"><CopyDocument /></el-icon>
                          </span>
                      
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="类型">
                    <template #default="scope">
                      <div v-if="scope.row.isFile == 0">-</div>
                      <div v-if="scope.row.fileType == 0">图片</div>
                      <div v-if="scope.row.fileType == 1">音频</div>
                      <div v-if="scope.row.fileType == 2">视频</div>
                      <div v-if="scope.row.fileType == 3">文档</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="文件大小">
                    <template #default="scope">
                      <div v-if="scope.row.isFile == 0">-</div>
                      <div v-else>{{ scope.row.fileSize }}</div>
                    </template>
                  </el-table-column>

                  <el-table-column label="创建时间">
                    <template #default="scope">
                      <div v-if="scope.row.isFile == 0">-</div>
                      <div v-else>{{ scope.row.creationDate }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="上传用户" width="250px">
                    <template #default="scope">
                      <div>
                        <div v-if="scope.row.isFile == 0">-</div>
                        <div v-else>{{ scope.row.createdAccount }}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column width="200px" label="操作">
                    <template #default="scope">
                      <div style="display: flex; align-items: baseline">
                        <el-button
                          v-if="scope.row.isFile == 1"
                          link
                          type="primary"
                          size="small"
                          style="
                            width: 20px;
                            height: 36px;
                            margin: 0 6px;
                            color: rgb(13, 174, 255);
                          "
                          @click="preview(scope.row.id)"
                          v-has="'materialPreview'"
                        >
                          预览
                        </el-button>
                        <el-button
                          link
                          type="primary"
                          size="small"
                          style="
                            width: 30px;
                            height: 36px;
                            color: rgb(13, 174, 255);
                          "
                          @click="move(scope.row.id)"
                          v-has="'materialMove'"
                        >
                          移动
                        </el-button>
                        <el-button
                          link
                          type="primary"
                          size="small"
                          style="
                            width: 30px;
                            height: 36px;
                            color: rgb(13, 174, 255);
                          "
                          @click="delects(scope.row.id)"
                          v-has="'materialDelete'"
                        >
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页 -->
                <div class="demo-pagination-block" v-if="total">
                  <el-pagination
                    v-model:current-page="currentPage4"
                    v-model:page-size="pageSize4"
                    :page-sizes="[10, 20, 50, 100]"
                    :disabled="disabled"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import { ElMessage, ElMessageBox } from "element-plus";
import {
  CloseBold,
  Calendar,
  EditPen,
  CopyDocument,
  Close,
} from "@element-plus/icons-vue";
import OSS from "ali-oss";
import useClipboard from "vue-clipboard3";
const { toClipboard } = useClipboard();
import Cookies from "js-cookie";
import {
  sourceDirectory,
  sourceMaterialPage,
  sourceMaterial,
  sourceMaterialPut,
  sourcedeviceDirectory,
  sourcedeviceMaterialry,
  sourceMaterialPutEdit,
  delect,
  getCredit,
  alldelect,
} from "@/api/facility/index.ts";
import { storeToRefs } from "pinia";
import { useMainStore } from "../../store/main.ts";
import { decrypt } from "../../utils/crypto.ts";
export default {
  data() {
    return {
      fileList: [],
      file: null,
      ishowss: false,
      loses: true,
      ishows: true,
      tempCheckpoint: null, // 用来缓存当前切片内容
      uploadId: "",
      uploadStatus: null, // 进度条上传状态
      percentage: 0, // 进度条百分比
      uploadName: "", //Object所在Bucket的完整路径
      outerVisible: false,
      uploadLists: [],
      size: "",
      status: "",
      imageLimit: 10, // 图片大小限制为10MB
      videoLimit: 200, // 视频大小限制为200MB
      audioLimit: 10, // 音频大小限制为10MB
      documentLimit: 10, // 文档大小限制为10MB
      listData: "",
      isFile: "",
      selectedValue: "",
      options: [
        {
          value: 0,
          label: "图片",
        },
        {
          value: 1,
          label: "音频",
        },
        {
          value: 2,
          label: "视频",
        },
      ],
      objectVersionNumberd: "",
      showEditFileNameButton: null,
      dialogTableVisible: false,
      rowId: "",
      catalogue: "",
      ishome: false,
      centerDialogVisible: false,
      monickerInfo: "",
      length: "",
      isdone: false,
      isdelect: true,
      pidss: "",
      isFileid: "",
      name: "",
      pageSize4: 10,
      currentPage4: 1,
      form: {
        name: "新建文件夹",
        pid: 0,
        monicker: "",
      },
      multipleTableRef: "",
      videoDuration: 0, //时长
      dialogFormVisible: false,
      formLabelWidth: "120px",
      fileExtension: "",
      editInfo: "",
      ides: "",
      total: 0,
      listData: "",
      genOpenInfo: "",
      losess: false,
      visible: false,
      ager: 0,
      input1: "",
      objectVersionNumber: "",
      OSSKEY: "",
      delectId: "",
      size: "",
      add: "",
    };
  },
  components: {
    CloseBold,
    Calendar,
    EditPen,
    CopyDocument,
    Close,
  },
  created() {
    this.genOpen();
    this.paging();
    this.getCredits();
  },
  methods: {
    // 预览
    async preview(id) {
      let result = await sourcedeviceMaterialry(id);
      console.log(result);
      if (result.data.code == 1) {
        this.size = result.data.data.fileSize;
        this.dialogTableVisible = true;
        function formatFileSize(fileSize) {
          fileSize = fileSize / (1024 * 1024);

          if (fileSize >= 1) {
            fileSize = fileSize.toFixed(2) + " MB";
          } else if (fileSize >= 1 / 1024) {
            fileSize = (fileSize * 1024).toFixed(2) + " KB";
          } else {
            fileSize = (fileSize * 1024 * 1024).toFixed(2) + " B";
          }

          return fileSize;
        }
        result.data.data.fileSize = formatFileSize(result.data.data.fileSize);

        this.editInfo = result.data.data;
      }
    },
    // 多个删除素材
    async delectClick() {
      let id = this.delectId;
      let first88 = localStorage.getItem("objectVersionNumberd");
      const [firstData] = first88.split(",");
      this.pidss = firstData;
      ElMessageBox.confirm("是否确认删除", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await alldelect(id);
          if (res.data.code == 1) {
            this.paging();
            this.genOpen();
            ElMessage({
              message: res.data.msg,
              type: "success",
              duration: "1000",
            });
          } else {
            ElMessage({
              message: res.data.msg,
              type: "error",
              duration: "1000",
            });
          }
        })
        .catch(() => {});
    },
    // 获取阿里云key
    async getCredits() {
      let res = await getCredit();
      this.OSSKEY = res.data.data;
      let key = decrypt(this.OSSKEY.accessKeyId);
      let iv = decrypt(this.OSSKEY.accessKeySecret);
      console.log(key);

      const client = new OSS({
        accessKeyId: key,
        accessKeySecret: iv,
        bucket:this.OSSKEY.bucket,
        region: this.OSSKEY.region,
        secure: true,
      });
    },
    truncateText(text, lines) {
      let str = text.trim();
      if (str.length > 2 * lines) {
        // 截取前两行的内容
        str = str.split("\n").slice(0, lines).join("\n");
        // 如果后面还有内容，则在末尾添加省略号
        if (str.length < text.length) {
          str += "...";
        }
      }
      return str;
    },
    // 放大
    btnlocses() {
      this.loses = !this.loses;
      this.losess = !this.losess;
      this.visible = false;
      this.outerVisible = true;
    },
    //  缩小
    btnlocse() {
      this.loses = !this.loses;
      this.losess = !this.losess;
      this.visible = true;
      this.outerVisible = false;
    },
    // 获取点击的目录id
    openId(ids) {
      localStorage.setItem("objectVersionNumberd", ids);
      this.pidss = ids;
      this.paging();
    },
    // 下拉搜索
    buootClick(val) {
      this.selectedValue = val;
      this.paging();
    },
    // 获取目录
    async genOpen() {
      let res = await sourcedeviceDirectory();
      if (res.data.code == 1) {
        // 辅助函数：递归获取所有层级节点
        function getNodes(data) {
          let result = [];
          for (let i = 0; i < data.length; i++) {
            let node = data[i];
            result.push({ id: node.id, name: node.name });
            if (node.childNode && node.childNode.length) {
              result = result.concat(getNodes(node.childNode));
            }
          }
          return result;
        }
        this.genOpenInfo = getNodes(res.data.data);
      }
      if (!this.pidss) {
        this.pidss = res.data.data.map((e) => {
          if (e.isFile == 0) {
            return e.id;
          }
        });
      }

      this.paging();
    },
    // 搜索
    SearchClick() {
      this.paging();
    },
    // 分页
    async paging() {
      let that = this;
      const pageSize = that.pageSize4;
      const pageNum = that.currentPage4;
      const directoryId = this.pidss;
      let data = {
        directoryId,
        pageSize,
        pageNum,
        fileType: that.selectedValue,
        keyword: this.input1,
      };
      let res = await sourceMaterialPage(data);
      if (res.data.code == 1) {
        res.data.data.content.map((item) => {
        if (item.fileType == 2 && item.isFile == 1) {
          item.fileUrl =
            item.fileUrl +
            "?x-oss-process=video/snapshot,t_10000,m_fast,h_200,w_200";
        } else if (item.fileType == 0 && item.isFile == 1)
          item.fileUrl =
            item.fileUrl + "?x-oss-process=image/resize,m_fill,h_50,w_50";
      });
      this.listData = res.data.data.content;
        this.total = res.data.data.totalElements;
        res.data.data.content.forEach((item) => {
          if (item.isFile == 0) {
            let add = [];
            add = item.id;
            this.ides = add;
          }
        });
        function formatFileSize(fileSize) {
          fileSize = fileSize / (1024 * 1024);
          if (fileSize >= 1) {
            fileSize = fileSize.toFixed(2) + " MB";
          } else if (fileSize >= 1 / 1024) {
            fileSize = (fileSize * 1024).toFixed(2) + " KB";
          } else {
            fileSize = (fileSize * 1024 * 1024).toFixed(2) + " B";
          }
          return fileSize;
        }
        res.data.data.content.forEach((item) => {
          if (item.fileSize) {
            // 将 fileSize 从字节转换为兆字节
            item.fileSize = formatFileSize(item.fileSize); // 四舍五入保留两位小数
          }
        });
        that.listData = res.data.data.content;
      }
    },
    // 粘贴
    async paste() {
      this.objectVersionNumberd = localStorage.getItem("objectVersionNumberd");
      this.delectId = localStorage.getItem("delectId");
      const { id, ids } = storeToRefs(useMainStore());
      // 拿到第一个id
      const numbers = this.objectVersionNumberd.split(","); // 将字符串拆分成数字数组
      let first88 = localStorage.getItem("objectVersionNumberd"); //
      for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] === "88") {
          first88 = numbers[i];
          break; // 找到第一个 "88" 后终止循环
        }
      }
      let data = {
        id: first88,
        ids: [this.delectId],
      };
      this.ishome = false;
      let res = await sourceMaterialPut(data);
      if (res.data.code == 1) {
        this.pidss = first88;
        this.centerDialogVisible = false;
        this.paging();
        ElMessage({
          message: res.data.msg,
          type: "success",
          duration: "1000",
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: "error",
          duration: "1000",
        });
      }
    },
    async opeName() {
      const transformedId = `${this.pidss}`; // 使用模板字符串将id转换为字符串
      let data = {
        name: this.form.name,
        directoryId: transformedId,
        isFile: 0,
      };
      let res = await sourceMaterial(data);
      if (res.data.code == 1) {
        this.dialogFormVisible = false;
        this.paging();
        this.genOpen();

        ElMessage({
          message: res.data.msg,
          type: "success",
          duration: "1000",
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: "error",
          duration: "1000",
        });
      }
    },
    // 点击文件夹
    openClicks(val) {
      localStorage.setItem("objectVersionNumberd", val.id);
      if (val.isFile == 0) {
        this.pidss = val.id;
      }
      this.paging();
    },
    // 关闭创建目录弹框清空数
    closeClick() {},
    // 鼠标经过
    mouseEnter(row) {
      this.showEditFileNameButton = true;
      this.rowId = row.id; //赋值行id，便于页面判断
    },
    //鼠标移出单元格事
    mouseLeave(row) {
      this.showEditFileNameButton = false;
      this.rowId = "";
    },
    // 确认修改按钮
    async monickerClick() {
      let data = {
        directoryId: this.monickerInfo.directoryId,
        id: this.monickerInfo.id,
        name: this.form.monicker,
        fileSize: this.size,
        fileSource: this.monickerInfo.fileSource,
        fileSuffix: this.monickerInfo.fileSuffix,
        fileType: this.monickerInfo.fileType,
        fileUrl: this.monickerInfo.fileUrl,
        isFile: this.isFile,
        objectVersionNumber: this.objectVersionNumber,
      };
      const regex = /^[\u4E00-\u9FA5A-Za-z0-9_-]{1,32}$/;
      if (regex.test(this.form.monicker)) {
        let res = await sourceMaterialPutEdit(data);
        if (res.data.code == 1) {
          this.centerDialogVisible = false;
          this.paging();

          ElMessage({
            message: res.data.msg,
            type: "success",
            duration: "1000",
          });
        } else {
          ElMessage({
            message: res.data.msg,
            type: "error",
            duration: "1000",
          });
        }
      } else {
        ElMessage({
          message: "请输入有效的素材名称",
          type: "error",
          duration: "1000",
        });
      }
    },
    // 当前页数
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.paging();
    },
    // 每一页条数
    handleSizeChange(val) {
      this.pageSize4 = val;
      this.paging();
    },
    // 表格
    handleSelectionChange(val) {
      const { id, ids } = storeToRefs(useMainStore());

      this.delectId = val.map((e) => e.id);
      localStorage.setItem("delectId", this.delectId);
      id.value = this.delectId;
      this.objectVersionNumberd = val.map((e) => e.directoryId);
      ids.value = this.objectVersionNumberd;

      localStorage.setItem("objectVersionNumberd", ids.value);
      this.isdone = true;
      if (this.delectId.length > 0) {
        this.isdelect = false;
      } else {
        this.isdelect = true;
        this.ishome = false;
      }
      this.length = val.length;
      val.forEach((item) => {
        (this.pidss = item.id), (this.isFileid = item.isFile);
        this.name = item.name;
      });
    },
    // 修改文件名弹窗
    async handleClick(val) {
      this.objectVersionNumber = val.row.objectVersionNumber;
      this.isFile = val.row.isFile;
      this.centerDialogVisible = true;
      this.form.monicker = val.row.name;
      this.monickerInfo = val.row;
      this.size = val.fileSize;
    },
    // 移动
    move(val) {
      localStorage.setItem("delectId", val);
      if (this.isdelect.length > 0) {
        this.ishome = false;
      } else {
        this.ishome = true;
      }
    },
    moves() {
      if (this.isdelect.length > 0) {
        this.ishome = false;
      } else {
        this.ishome = true;
      }
    },
    // 复制
    async copy(url) {
      try {
        await toClipboard(url);
        ElMessage({
          message: "复制成功",
          type: "success",
          duration: "1000",
        });
      } catch (e) {
        ElMessage({
          message: "您的浏览器不支持复制：",
          type: "error",
          duration: "1000",
        });
      }
    },
    // 单个删除素材
    async delects(id) {
      ElMessageBox.confirm("是否确认删除", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await delect(id);
          if (res.data.code == 1) {
            this.paging();
            this.genOpen();
            ElMessage({
              message: res.data.msg,
              type: "success",
              duration: "1000",
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.msg,
              duration: "1000",
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消删除",
            duration: "1000",
          });
        });
    },
    // 取消分片上传事件
    async abortMultipartUpload() {
      const client = new OSS({
        accessKeyId: decrypt(this.OSSKEY.accessKeyId),
        accessKeySecret: decrypt(this.OSSKEY.accessKeySecret),
        bucket: this.OSSKEY.bucket,
        region: this.OSSKEY.region,
        secure: true,
      });
      window.removeEventListener("online", this.resumeUpload);
      const name = this.uploadName; // Object所在Bucket的完整路径。
      const uploadId = this.upload; // 分片上传uploadId。
      const result = await client.abortMultipartUpload(name, uploadId);
    },
    // 暂停分片上传。
    stopUplosd() {
      let key = decrypt(this.OSSKEY.accessKeyId);
      let iv = decrypt(this.OSSKEY.accessKeySecret);
      const client = new OSS({
        accessKeyId: key,
        accessKeySecret: iv,
        bucket: this.OSSKEY.bucket,
        region: this.OSSKEY.region,
        secure: true,
      });
      window.removeEventListener("online", this.resumeUpload); // 暂停时清除时间监听
      let result = client.cancel();
      this.ishows = false;
      this.ishowss = true;
      this.ager++;
    },
    // 切片上传
    async multipartUpload() {
      let key = decrypt(this.OSSKEY.accessKeyId);
      let iv = decrypt(this.OSSKEY.accessKeySecret);
      const client = new OSS({
        accessKeyId: key,
        accessKeySecret: iv,
        bucket: this.OSSKEY.bucket,
        region: this.OSSKEY.region,
        secure: true,
      });
      if (!this.file) {
        this.$message.error("请选择文件", { duration: 1000 });
        return;
      }
      this.uploadStatus = null;
      //<!-- const storeAs = `${Date.now()}-${file.name}`; -->
      this.percentage = 0;
      const currentDate = new Date();
      const year = currentDate.getFullYear(); // 获取当前年份
      const month = currentDate.getMonth() + 1; // 获取当前月份，需要注意月份从 0 开始计数
      const day = currentDate.getDate(); // 获取当前日0?
      const storeAs = `${year}/${month}/${day}/`;
      let time = new Date().getTime();
      this.add = `${storeAs}${time}${"."}${this.file.name.substring(
        this.file.name.lastIndexOf(".") + 1
      )}`;
      //   image/png  image/jpeg image/jpg
      try {
        //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
        let result = await client.multipartUpload(this.add, this.file, {
          progress: (p, checkpoint) => {
            this.tempCheckpoint = checkpoint;
            this.upload = this.file.uid;
            this.uploadName = storeAs;
            this.percentage = p * 100;
            this.size = (this.file.size / 1024 / 1024).toFixed(2) + "MB";
            this.status = Math.floor(Math.random() * 900) + 100 + "KB/s";

            this.uploadLists = [
              {
                size: this.size,
                status: this.status,
                uploadName: this.uploadName,
                percentage: this.percentage,
              },
            ];
            // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
          },
        });
        if (result.res.status == 200) {
          let url = result.res.requestUrls[0];
          var baseURL = url.split("?")[0]; //把?后面的截取掉
          let data = {
            directoryId: this.pidss.toString(), //目录id
            fileSource: 0, //文件来源
            fileUrl: baseURL, //文件路径
            name: this.file.name.split(".")[0],
            fileSuffix: this.file.name.substring(
              this.file.name.lastIndexOf(".") + 1
            ), //后缀名
            isFile: 1,
          };
          let res = await sourceMaterial(data);
          this.paging();
          if (res.data.code == 1) {
            this.$message.success("上传成功", { duration: 1000 });
            this.paging();
          }
        }
      } catch (e) {
        window.addEventListener("online", this.resumeUpload); // 该监听放在断网的异常处理
        // 捕获超时异常。
        if (e.code === "ConnectionTimeoutError") {
          this.$message.error("网络异常,请稍后再试");
          // 请求超时异常处理
          this.uploadStatus = "exception";
          // do ConnectionTimeoutError operation
        }
      }
    },
    // 恢复上传。
    async resumeUpload() {
      let key = decrypt(this.OSSKEY.accessKeyId);
      let iv = decrypt(this.OSSKEY.accessKeySecret);
      const client = new OSS({
        accessKeyId: key,
        accessKeySecret: iv,
        bucket:this.OSSKEY.bucket,
        region: this.OSSKEY.region,
        secure: true,
      });
      const currentDate = new Date();
      const year = currentDate.getFullYear(); // 获取当前年份
      const month = currentDate.getMonth() + 1; // 获取当前月份，需要注意月份从 0 开始计数
      const day = currentDate.getDate(); // 获取当前日0?
      const storeAs = `${year}${month}${day}/${Date.now()}${"."}${
        this.fileExtension
      }`;
      window.removeEventListener("online", this.resumeUpload);
      this.ishows = true;
      this.ishowss = false;
      if (!this.tempCheckpoint) {
        this.$message.error("请先上传", { duration: 1000 });
        return;
      }
      this.uploadStatus = null;
      return;
      try {
        let result = await client.multipartUpload(this.file.name, this.file, {
          headers: {
            "Content-Disposition": "inline",
            // "Content-Type": this.file.type, //注意：根据图片或者文件的后缀来设置，我试验用的‘.png’的图片，具体为什么下文解释
          },
          progress: (p, checkpoint) => {
            this.percentage = p * 100;

            this.tempCheckpoint = checkpoint;
            this.size = (this.file.size / 1024 / 1024).toFixed(2) + "MB";
            this.status = Math.floor(Math.random() * 900) + 100 + "KB/s";
            this.uploadLists = [
              {
                size: this.size,
                status: this.status,
                uploadName: this.uploadName,
                percentage: this.percentage,
              },
            ];
          },
          checkpoint: this.tempCheckpoint,
          meta: { year: 2020, people: "dev" },
          mime: this.file.type,
        });
      } catch (e) {}
    },
    // 选择文件发生改变
    handleChange(file, fileList) {
      this.fileExtension = file.raw.name.substring(
        file.raw.name.lastIndexOf(".") + 1
      );
      // 文件类型image/png"
      if (
        file.raw.type !== "image/png" &&
        file.raw.type !== "image/jpeg" &&
        file.raw.type !== "image/jpg" &&
        file.raw.type !== "video/mp4" &&
        file.raw.type !== "audio/mpeg" &&
        file.raw.type !== "application/pdf"
      ) {
        ElMessage({
          message:
            "仅允许选择视频（mp4）、音频(mp3)、图片(jpg、jpeg、png)、文件(PDF)",
          type: "warning",
          duration: "1000",
        });
        return;
      }
      const isImage = file.raw.type.startsWith("image/");
      const isVideo = file.raw.type.startsWith("video/");
      const isAudio = file.raw.type.startsWith("audio/");
      const isDocument = file.raw.type.startsWith("application/pdf"); // 假设文档类型为PDF
      let limit;
      let fileType;
      if (isImage) {
        limit = this.imageLimit;
        fileType = "图片";
      } else if (isVideo) {
        limit = this.videoLimit;
        fileType = "视频";
      } else if (isAudio) {
        limit = this.audioLimit;
        fileType = "音频";
      } else if (isDocument) {
        limit = this.documentLimit;
        fileType = "文档";
      }
      if (file.size > limit * 1024 * 1024) {
        this.$message.warning(`上传的${fileType}大小不能超过${limit}MB`);
        this.$refs.upload.clearFiles();
        return;
      }
      this.fileList = fileList.filter((row) => row.uid == file.uid);
      this.file = file.raw;
      if (this.file) {
        this.multipartUpload();
        this.outerVisible = true;
      }

    },
    // 高亮表头单元格的方法
    highlightHeaderCell({ column, columnIndex, rowIndex }) {
      if (columnIndex === 0) {
        // 第一列高亮
        return "highlight-cell";
      }
    },
    handleRemove(file, fileList) {
      this.percentage = 0; //进度条置空
      this.fileList = [];
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-input input::selection {
  background-color: #79bbff;
}
::v-deep .el-button--small {
  --el-button-size: 24px;
  height: var(--el-button-size);
  padding: 0px 0px;
  font-size: 12px;
  border-radius: calc(var(--el-border-radius-base) - 1px);
}
::v-deep .el-dialog__header {
  padding: var(--el-dialog-padding-primary);
  padding-bottom: 10px;
  margin-right: -8px;
}
::v-deep
  .el-descriptions__body
  .el-descriptions__table.is-bordered
  .el-descriptions__cell {
  border: var(--el-descriptions-table-border);
  padding: 8px 11px;
  /* margin-left: 0px; */
  text-align: center;
}
::v-deep .el-breadcrumb {
  font-size: 14px;
  line-height: 1;
  margin: 5px 0;
}
.table-pagination-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.el-table {
  width: 100%;
  margin-bottom: 20px;
}
:deep(.el-table__row):hover .--table-column-icon {
  display: inline-block;
}

.--table-column-icon {
  display: none;
  margin-left: 10px;
  cursor: pointer;

  &:hover {
    :deep(.el-icon) {
      color: var(--el-color-primary);
    }
  }
}
.el-pagination {
  width: 100%;
}
// @import '@element-plus/lib/theme-chalk/el-icon.css';
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
// 上箭头

// 下滑
.add {
  width: 3px;
  height: 18px;

  /* 主色 */

  background: #0daeff;
  border-radius: 3px;

  /* Inside auto layout */

  flex: none;
  order: 0;
  flex-grow: 0;
}
/* 自定义表头样式 */
.table-header-class th {
  color: #fff;
  background: #333;
}
::v-deep .el-table th.el-table__cell.is-leaf {
  border-bottom: none; //清除表格头部下划线
}
.el-table__body-wrapper ::v-deep .el-table__row .el-table__cell {
  border-bottom: none !important;
}
.lunde {
  white-space: nowrap; /* 强制内容在一行内显示 */
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出内容显示省略号 */
  max-height: 50px; /* 设置单元格最大高度 */
  max-width: 200px;
  line-height: 25px; /* 设置单元格中行高，使内容垂直居中 */
}
.box {
  background-color: #fff;
  height: 100%;
  .box-heard {
    margin: 0 20px;
  }
}
.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
